﻿using Service.Domain.Entities;
using Service.Domain.Entities.User;
using Service.Domain.Interfaces;
using Service.Domain.Interfaces.Repositories;
using Service.Domain.Shared.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service.Repository.User
{
    public class PermissionRepository : IPermissionRepository
    {
        readonly IDbContext context;

        public PermissionRepository(IDbContext context) {
            this.context = context;
        }

        public async Task<IEnumerable<Permission>> GetUserPermissions(List<int> roleIds)
        {
            string sql = @"SELECT
                    p.`code`,
                    p.componentPath,
                    p.breadcrumbName,
                    p.isMenu,
                    p.label,
                    p.path,
                    p.id,
                    p.pid,
                    PA.`code` AS `ActionCode`,
                    PA.id AS `ActionId`
                FROM RolePermissions AS `RP`
                JOIN Permission AS `P` ON RP.permissionId = P.id
                LEFT JOIN RolePermissionActions AS `RPA` ON RP.id = RPA.rolePermissionId
                LEFT JOIN PermissionActions AS `PA` ON RPA.permissionActionId = PA.id
                WHERE P.valid = 1 AND PA.valid = 1 AND RP.roleId IN (@ROLEIDS);";

            return await context.QueryAsync<Permission, PermissionAction, Permission>(sql, (p, pa) =>
            {
                return p;
            }, new { ROLEIDS = roleIds });
        }
    }
}
